﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace KBCommon.Utility
{
    //内存释放类
    public class RevokeMemory
    {
        [DllImport("kernel32.dll")]
        private static extern bool GetProcessWorkingSetSize(IntPtr proc, out int min, out int max);
        [DllImport("kernel32.dll")]
        private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

        public static void ReduceMemory()
        {
            GCCollect();
            System.Diagnostics.Process.GetCurrentProcess().MinWorkingSet = new System.IntPtr(5);
        }

        private static void GCCollect()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

        public static void ReduceMemoryFootPrint()
        {
            int currentMinWorkingSetValue = 0;
            int currentMaxWorkingSetValue = 0;
            Process currentProcess = Process.GetCurrentProcess();

            try
            {
                if (GetProcessWorkingSetSize(currentProcess.Handle, out currentMinWorkingSetValue, out currentMaxWorkingSetValue))
                {
                    GCCollect();
                    currentProcess.MinWorkingSet = (IntPtr)currentMinWorkingSetValue;
                }
            }
            catch
            {
                string additionalInfo = "MinWorkingSetvalue is set to: " + currentMinWorkingSetValue.ToString();
                additionalInfo += " Process In Error: " + currentProcess.ProcessName;
            }
        }
    }  
}
